package com.njupt.HashTable;

import java.util.HashSet;
import java.util.Set;

public class IsHappy {

    public boolean isHappy(int n) {
        int result = 0;
        Set<Integer> integers = new HashSet<>();
        while(true){

            result = calDivNum(n);

            if(result == 1){
                return true;
            } else if (integers.contains(result)) {
                return false;
            } else {
                integers.add(result);
                n = result;
            }
        }

//        return false;
    }

    public boolean isHappy1(int n) {
        int result = 0;
        Set<Integer> integers = new HashSet<>();
        while(n != 1 && !integers.contains(n)){
            integers.add(n); //为了避免判断冲突可以将第一个n放进去
            n = calDivNum(n);


        }

        return n==1;
    }

    public int calDivNum(int num){
        int result = 0;
        int sum = 0;
        while(num != 0 ){
            result = num%10;
            sum += result * result;
            num = num/10;
        }
        return sum;
    }


    public static void main(String[] args) {
        IsHappy test = new IsHappy();
        System.out.println(test.isHappy1(19));
    }
}
